require.config({
  paths: {
    "zepto": "/js/zepto.min",
    "http": "/js/http.min",
    "config": "/js/config.min"
  }
});


require(['http', 'config', 'zepto'], function (http, config, $) {

  document.getElementById('img').addEventListener('change', function () {
    var reader = new FileReader();
    reader.onload = function (e) {
      //调用图片压缩方法：compress();
      // compress();
    };
    reader.readAsDataURL(this.files[0]);
    console.log(this.files[0]);
    var fileSize = Math.round(this.files[0].size / 1024 / 1024); //以M为单位
    //this.files[0] 该信息包含：图片的大小，以byte计算 获取size的方法如下：this.files[0].size;
  }, false);

  function compress(res, fileSize) { //res代表上传的图片，fileSize大小图片的大小
    var img = new Image(),
      maxW = 640; //设置最大宽度

    img.onload = function () {
      var cvs = document.createElement('canvas'),
        ctx = cvs.getContext('2d');

      if (img.width > maxW) {
        img.height *= maxW / img.width;
        img.width = maxW;
      }

      cvs.width = img.width;
      cvs.height = img.height;

      ctx.clearRect(0, 0, cvs.width, cvs.height);
      ctx.drawImage(img, 0, 0, img.width, img.height);

      var compressRate = getCompressRate(1, fileSize);

      var dataUrl = cvs.toDataURL('image/jpeg', compressRate);

      document.body.appendChild(cvs);
      console.log(dataUrl);
    }

    img.src = res;
  }

  function getCompressRate(allowMaxSize, fileSize) { //计算压缩比率，size单位为MB
    var compressRate = 1;

    if (fileSize / allowMaxSize > 4) {
      compressRate = 0.5;
    } else if (fileSize / allowMaxSize > 3) {
      compressRate = 0.6;
    } else if (fileSize / allowMaxSize > 2) {
      compressRate = 0.7;
    } else if (fileSize > allowMaxSize) {
      compressRate = 0.8;
    } else {
      compressRate = 0.9;
    }

    return compressRate;
  }

});